<script lang="ts" setup>
import {
  IconSave,
  VButton,
  VModal,
  VSpace,
  Toast,
} from "@halo-dev/components";
import { FormKit } from "@formkit/vue";
import { computed, nextTick, ref, watch } from "vue";
import type { ProductType } from "@console/types";
import { productTypeApiClient } from "@console/api/product";
import { cloneDeep } from "lodash-es";
import { setFocus } from "@console/formkit/utils/focus";
import { submitForm } from "@console/formkit/utils/submit";

const props = withDefaults(
  defineProps<{
    visible: boolean;
    productType?: ProductType;
  }>(),
  {
    visible: false,
    productType: undefined,
  }
);

const emit = defineEmits<{
  "update:visible": [visible: boolean];
  "close": [];
}>();

const initialFormState: ProductType = {
  spec: {
    displayName: "",
    description: "",
    images: [],
    priority: 0,
  },
  apiVersion: "content.halo.run/v1alpha1",
  kind: "ProductType",
  metadata: {
    name: "",
    generateName: "product-type-",
  },
};

const formState = ref<ProductType>(cloneDeep(initialFormState));
const saving = ref(false);
const formVisible = ref(false);

const isUpdateMode = computed(() => {
  return !!formState.value?.metadata?.creationTimestamp;
});

const modalTitle = computed(() => {
  return isUpdateMode.value ? "编辑产品类型" : "新建产品类型";
});

// computed值用于处理string/number转换
const priorityStr = computed({
  get: () => {
    const priority = formState.value?.spec?.priority;
    return priority !== null && priority !== undefined ? String(priority) : '';
  },
  set: (value: string) => {
    if (formState.value?.spec) {
      formState.value.spec.priority = value ? parseInt(value, 10) || 0 : 0;
    }
  }
});

const handleVisibleChange = (visible: boolean) => {
  emit("update:visible", visible);
  if (!visible) {
    emit("close");
  }
};

const handleSubmit = async () => {
  try {
    saving.value = true;

    // computed属性已自动处理类型转换

    if (isUpdateMode.value) {
      await productTypeApiClient.updateProductType({
        name: formState.value.metadata.name,
        productType: formState.value,
      });
    } else {
      // Generate name from displayName if not provided
      if (!formState.value.metadata.name) {
        const displayName = formState.value.spec.displayName;
        const name = displayName
          .toLowerCase()
          .replace(/[^a-z0-9\u4e00-\u9fa5]/g, "-")
          .replace(/-+/g, "-")
          .replace(/^-|-$/g, "");
        formState.value.metadata.name = name || formState.value.metadata.generateName || 'product-type-';
      }
      
      await productTypeApiClient.createProductType({
        productType: formState.value,
      });
    }

    Toast.success("保存成功");
    handleVisibleChange(false);
  } catch (error) {
    console.error("Failed to save product type", error);
    Toast.error("保存失败");
  } finally {
    saving.value = false;
  }
};

const handleResetForm = () => {
  formState.value = cloneDeep(initialFormState);
};

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      formVisible.value = true;
    } else {
      setTimeout(() => {
        formVisible.value = false;
        handleResetForm();
      }, 200);
    }
  }
);

watch(
  () => props.productType,
  (productType) => {
    if (productType) {
      formState.value = cloneDeep(productType);
      // 确保 spec 对象存在
      if (!formState.value.spec) {
        formState.value.spec = {
          displayName: "",
          description: "",
          images: [],
          priority: 0,
        };
      }
      // 确保 priority 字段有默认值
      if (formState.value.spec.priority === null || formState.value.spec.priority === undefined) {
        formState.value.spec.priority = 0;
      }
    } else {
      handleResetForm();
    }
  },
  { immediate: true }
);

watch(
  () => formVisible.value,
  (visible) => {
    if (visible) {
      nextTick(() => {
        setFocus("displayNameInput");
      });
    }
  }
);
</script>

<template>
  <VModal
    :visible="visible"
    :width="700"
    :title="modalTitle"
    :centered="false"
    @update:visible="handleVisibleChange"
  >
    <template #actions>
      <VSpace>
        <VButton
          :loading="saving"
          type="primary"
          @click="submitForm('product-type-form', handleSubmit)"
        >
          <template #icon>
            <IconSave class="h-4 w-4" />
          </template>
          保存
        </VButton>
      </VSpace>
    </template>

    <FormKit
      v-if="formVisible"
      id="product-type-form"
      v-model="formState.spec"
      name="product-type-form"
      :actions="false"
      type="form"
      :config="{ validationVisibility: 'submit' }"
      @submit="handleSubmit"
    >
      <FormKit
        id="displayNameInput"
        v-model="formState.spec.displayName"
        :label="'名称'"
        type="text"
        name="displayName"
        validation="required|length:1,50"
      ></FormKit>
      
      <FormKit
        v-model="formState.spec.description"
        :label="'描述'"
        type="textarea"
        name="description"
        :rows="5"
        validation="length:0,200"
      ></FormKit>
      
      <FormKit
        v-model="formState.spec.images"
        :label="'产品图片'"
        type="attachment"
        name="images"
        :multiple="true"
        :accepts="['image/*']"
        :help="'可上传多张图片用于展示产品类型'"
      ></FormKit>
      
      <FormKit
        v-model="priorityStr"
        :label="'优先级'"
        type="text"
        name="priority"
        :help="'数值越大优先级越高'"
        validation="number|min:0"
      ></FormKit>
      
      <FormKit
        v-if="isUpdateMode"
        v-model="formState.metadata.name"
        :label="'别名'"
        type="text"
        name="name"
        validation="required|length:1,63"
        :help="'用于标识产品类型的唯一名称，创建后不可修改'"
        :disabled="true"
      ></FormKit>
    </FormKit>
  </VModal>
</template>